package com.crop.back.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.crop.back.common.utils.UserHolder;
import static com.crop.back.common.utils.RedisConstants.LOGIN_TOKEN_KEY;
import static com.crop.back.common.utils.RedisConstants.LOGIN_TOKEN_TTL;
import com.crop.back.common.utils.RedisUtil;
import com.crop.back.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private RedisUtil redisUtil;

    private static final String TOKEN_KEY = "Admin-Token";

    public RefreshTokenInterceptor(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中cookie中的的token
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return true;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(TOKEN_KEY)) {
                token = cookie.getValue();
            }
        }
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2.基于TOKEN获取redis中的用户
        String tokenKey = LOGIN_TOKEN_KEY + token;
        Map<String, Object> adminMap = redisUtil.hgetAll(tokenKey);
        // 3.判断用户是否存在
        if (adminMap.isEmpty()) {
            //3.1 不存在放行即可
            return true;
        }
        // 5.将查询到的hash数据转为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(adminMap, new UserDTO(), false);
        // 6.存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(userDTO);
        // 7.刷新token有效期
        redisUtil.expireWithTimeUnit(tokenKey, LOGIN_TOKEN_TTL, TimeUnit.SECONDS);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
